package com.axonactive.yolo.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.axonactive.yolo.dto.JSONobject;

public class IOUtil {
	private static final Logger LOGGER = Logger.getLogger(IOUtil.class);
	private static ObjectMapper mapper = new ObjectMapper();

	// Read response in local file. Using for test
	public static String readJSONResponseFromFile(String path)
			throws IOException {
		BufferedReader fileReader = new BufferedReader(new FileReader(path));
		String line = "";
		String result = "";
		while ((line = fileReader.readLine()) != null) {
			result += line;
		}
		return result;
	}

	// Execute a jar file by location.
	public static List<String> executeProgram(String path) {
		List<String> rs = new ArrayList<String>();
		try {
			Process proc = Runtime.getRuntime().exec("java -jar " + path);
			// Then retrieve the process output
			BufferedReader bin = new BufferedReader(new InputStreamReader(
					proc.getInputStream()));
			String line = null;
			while ((line = bin.readLine()) != null) {
				LOGGER.info(line);
				// result += line;
				rs.add(line);
			}
			return rs;
		} catch (IOException ex) {
			LOGGER.error("IO error", ex);
			rs.add(ex.getMessage());
			return rs;
		}
	}

	public static String callToServer(String url)
			throws ClientProtocolException, IOException {
		String result = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response
				.getEntity().getContent()));
		String line = "";
		while ((line = rd.readLine()) != null) {
			result += line;
		}
		return result;
	}

	public static String call(String url) throws IOException,
			InterruptedException {
		URL requestUrl = new URL(url);
		URLConnection con = requestUrl.openConnection();
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		StringBuilder sb = new StringBuilder();
		int cp;
		try {
			while ((cp = rd.read()) != -1) {
				sb.append((char) cp);
			}
		} catch (Exception e) {
		}
		String json = sb.toString();
		return json;
	}

	public static void logToFile(String message) {
		try {
			File file = new File("//root//logger.txt");
			// File file = new File("C:\\Users\\pqtrung\\logger.txt");
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(message);
			bw.newLine();
			bw.close();
		} catch (IOException e) {
			// e.printStackTrace();
		}
	}

	public static String toJSON(JSONobject jsonObj) throws JsonGenerationException, JsonMappingException, IOException {
		return mapper.writeValueAsString((Object) jsonObj);
	}
}
